import qs from 'qs'

const BASE_URL = 'https://api.huhuiyu.top'
const TOKEN_KEY = '_token'


const LocalToken = {
	loadToken: () => {
		let token = uni.getStorageSync(BASE_URL + TOKEN_KEY)
		return token ? token : ''
	},
	saveToken: (data) => {
		if (data && data.token) {
			uni.setStorageSync(BASE_URL + TOKEN_KEY, data.token)
		}
	},
	removeToken: () => {
		uni.removeStorageSync(BASE_URL + TOKEN_KEY)
	}
}

const MAX_FILE_SIZE = 5 * 1024 * 1024
const MAX_FILE_SIZE_MESSAGE = {
	code: 500,
	success: false,
	message: '上传文件大小不能超过' + MAX_FILE_SIZE / 1024 / 1024 + 'MB'
}

const api = {
	upload: (url, param, file, path, cb) => {
		console.log("====>", file, "====>", path)
		if (file.size > MAX_FILE_SIZE) {
			cb(MAX_FILE_SIZE_MESSAGE)
			return
		}
		uni.uploadFile({
			url: BASE_URL + url,
			filePath: path,
			name: "file",
			header: {
				'Authorization': LocalToken.loadToken(),
			},
			success: (resp) => {
				console.log("====>", resp)
				LocalToken.saveToken(resp.data)
				cb(resp.data)
			},
			fail: (err) => {
				console.log("====>", err)
				cb({
					code: 500,
					success: false,
					message: '网站忙，请稍后重试'
				})
			}
		})
	},
	get: (url, param, cb) => {
		api.ajax(url, param, cb, "GET")
	},
	post: (url, param, cb) => {
		api.ajax(url, param, cb, "POST")
	},
	delete: (url, param, cb) => {
		api.ajax(url, param, cb, "DELETE")
	},
	put: (url, param, cb) => {
		api.ajax(url, param, cb, "PUT")
	},
	patch: (url, param, cb) => {
		api.ajax(url, param, cb, "PATCH")
	},
	ajax: (url, param, cb, method) => {
		// get请求使用地址栏传递参数
		if (method.toUpperCase() === 'GET') {
			let reqdata = qs.stringify(param, {
				allowDots: true
			})
			url = `${url}?${reqdata}`
			param = ''
		}
		uni.request({
			url: BASE_URL + url,
			method: method,
			data: param,
			header: {
				'Authorization': LocalToken.loadToken(),
			},
			success: (resp) => {
				LocalToken.saveToken(resp.data)
				cb(resp.data)
			},
			fail: () => {
				cb({
					code: 500,
					success: false,
					message: '网站忙，请稍后重试'
				})
			}
		})
	},
	getUserLogo: (uid) => {
		return `${BASE_URL}/user/logo/${uid}`
	},
	getLoginUserLogo: (uid) => {
		return `${BASE_URL}user/logo`
	}
}

export default api

export {
	api,
	LocalToken,
	BASE_URL
}